package com.coocaa.ops.admin.v1.upload.util;

import com.coocaa.ops.common.tool.exception.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author bijiahao
 * @date : 2019/2/15.
 * @description
 */
@Slf4j
public class ImageAnalyzerUtil {

    public static String getImgResolution(String extName, MultipartFile mf) {
        String resolution = "0*0";
        try {
            resolution = getImgResolution(extName, mf.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resolution;
    }

    public static String getImgResolution(String extName, File file) {
        String resolution = "0*0";
        try {
            resolution = getImgResolution(extName, new FileInputStream(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return resolution;
    }

    public static String getImgResolution(String extName, InputStream inputStream) {
        int imgWidth = 0;
        int imgHeight = 0;
        try {
            if (".webp".equals(extName)) {
                //读取WEBP格式图片-动图需要前端进行读取再回传后端
                byte[] bytes = new byte[30];
                inputStream.read(bytes,0,bytes.length);
                imgWidth = ((int) bytes[27] & 0xff) << 8 | ((int) bytes[26] & 0xff);
                imgHeight = ((int) bytes[29] & 0xff) << 8 | ((int) bytes[28] & 0xff);
            } else if (".ico".equals(extName)) {

            } else {
                BufferedImage bufferedImage = ImageIO.read(inputStream);
                imgWidth = bufferedImage.getWidth();
                imgHeight = bufferedImage.getHeight();
            }
        } catch (IOException e) {
            log.error(ExceptionUtil.getStackTraceAsString(e));
        }
        String resolution = imgWidth + "*" + imgHeight;
        return resolution;
    }

    public static void main(String[] args) {
        String f = "/Users/bijiahao/test/20180111165605921901_13824x0.webp";
//        String f = "/Users/bijiahao/test/20170714151630045883_522x300.webp";
        String res = getImgResolution(".webp", new File(f));
        System.out.println(res);
    }

}
